package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;

import com.itheima.mapper.CheckgroupCheckitemMapper;
import com.itheima.mapper.SetMealCheckGroupMapper;
import com.itheima.pojo.CheckGroup;

import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import com.itheima.utils.HealthStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 检查组的业务层
 * @author: wangjingliang
 * @create: 2019-11-08 14:30
 **/
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImp implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private CheckgroupCheckitemMapper checkgroupCheckitemMapper;

    @Autowired
    private SetMealCheckGroupMapper setMealCheckGroupMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 对检查组的数据添加
     *
     * @param: CheckGroup
     * @return: null
     * @date: 2019/11/8
     */
    @Override
    public int add(int[] checkitemIds, CheckGroup checkGroup) {
        //添加时检查项与检查表的关联关系,必须对中间表进行添加
        String code = checkGroup.getCode();
        String name = checkGroup.getName();
        String helpCode = checkGroup.getHelpCode();

        //判断编码和名称是否已经存在
        int byCode = checkGroupMapper.findByCode(code);
        if (byCode > 0) {
            throw new RuntimeException("该编码已存在");
        }
        int byName = checkGroupMapper.findByName(name);
        if (byName > 0) {
            throw new RuntimeException("请该名称已存在");
        }
        int ByhelpCode = checkGroupMapper.findByHelpCode(helpCode);
        if (ByhelpCode > 0) {
            throw new RuntimeException("请该助记已存在");
        }

        //再插入检查组
        int add = checkGroupMapper.add(checkGroup);
        Integer id = checkGroup.getId();
        if (id == null) {
            throw new RuntimeException(MessageConstant.EXCEPION);
        } else {
            //存入redis中
            redisTemplate.boundListOps("checkGroupList").rightPush(checkGroup);


        }

        //先插入中间表

        if (checkitemIds != null || checkitemIds.length > 0) {
            for (int checkitemId : checkitemIds) {

                try {
                    checkgroupCheckitemMapper.addCheckGroupIdAndCheckitemIds(checkitemId, id);
                } catch (Exception e) {
                    throw new RuntimeException(MessageConstant.EXCEPION);
                }
            }
        }

        return add;
    }


    /**
     * 根据页码和当前显示页数进行分页查询
     *
     * @param: QueryPageBean
     * @return: null
     * @date: 2019/11/7
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        //判断参数是否存在
        if (currentPage < 1 || currentPage == null) {
            currentPage = 1;
        }
        if (pageSize < 0 || pageSize == null) {
            pageSize = 10;
        }
        if (queryString == null) {
            queryString = "";
        }
        //判断是否为null或者为" "
        if (HealthStringUtils.isEmpty(queryString)) {

            queryString = queryString.trim();
        }
        //基于mybatis的分页插件
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = checkGroupMapper.findPage("%" + queryString + "%");

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id进行查询
     *
     * @param:Integer id
     * @return: CheckGroup
     * @date: 2019/11/7
     */
    @Override
    public Map<String, Object> findCheckGroudAndCheckItemInfo(Integer id) {
        Map<String, Object> map = new HashMap<>();
        try {
            CheckGroup checkGroup = null;

            //直接从redis中进行查询
            List<CheckGroup> checkGroupList = redisTemplate.boundListOps("checkGroupList").range(0, -1);
            for (CheckGroup Group : checkGroupList) {
                if (Group.getId().equals(id)) {
                    checkGroup = Group;
                }
            }
            //获取检查项基本信息
            //从redis中获取检查项的集合数据
            List<CheckItem> checkItemList = redisTemplate.boundListOps("checkItemList").range(0, -1);

            Integer[] checkItemIds = checkgroupCheckitemMapper.findCheckItemIdsByCheckGroupId(id);
            map.put("checkGroup", checkGroup);
            map.put("checkItemList", checkItemList);
            map.put("checkItemIds", checkItemIds);
        } catch (Exception e) {
            throw new RuntimeException(MessageConstant.EXCEPION);
        }

        return map;
    }


    /**
     * 根据提供数据进行修改
     *
     * @param: CheckItem
     * @return: int
     * @date: 2019/11/7
     */
    @Override
    public int edit(int[] ids, CheckGroup checkGroup) {
        int edit = 0;
        //判断编码和名称是否为null或者是空
        String code = checkGroup.getCode();
        String name = checkGroup.getName();
        String helpCode = checkGroup.getHelpCode();
        //首先去判读是否和原来的一样,方法是根据id查询
        CheckGroup checkGroup1 = checkGroupMapper.findById(checkGroup.getId());

        if (!checkGroup1.getCode().equals(code)) {
            //判断编码和名称是否已经存在
            int byCode = checkGroupMapper.findByCode(code);
            if (byCode > 0) {
                throw new RuntimeException("该编码已存在");
            }
        }

        if (!checkGroup1.getName().equals(name)) {
            //判读是否能查询到其他的值
            int byName = checkGroupMapper.findByName(name);
            if (byName > 0) {
                throw new RuntimeException("请该名称已存在");
            }
        }
        if (!checkGroup1.getHelpCode().equals(helpCode)) {
            //判读是否能查询到其他的值
            int ByhelpCode = checkGroupMapper.findByHelpCode(helpCode);
            if (ByhelpCode > 0) {
                throw new RuntimeException("请该助记已存在");
            }
        }
        //对中间表进行修改
        try {
            if (ids != null && ids.length > 0) {
                checkgroupCheckitemMapper.deleteByCheckGroupId(checkGroup.getId());
                for (int checkitemId : ids) {
                    int i = checkgroupCheckitemMapper.addCheckGroupIdAndCheckitemIds(checkitemId, checkGroup.getId());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(MessageConstant.EXCEPION);
        }
        //进行修改
        edit = checkGroupMapper.edit(checkGroup);
        if (edit > 0) {

            //将集合储存到redis缓存中
            List<CheckGroup> checkGroupList = redisTemplate.boundListOps("checkGroupList").range(0, -1);
            for (CheckGroup Group : checkGroupList) {
                if (Group.getId().equals(checkGroup.getId())) {
                    redisTemplate.opsForList().remove("checkItemList", 1, Group);
                    redisTemplate.boundListOps("checkItemList").leftPush(checkGroup);
                }
            }

        }

        return edit;
    }


    /**
     * 根据id进行删除
     *
     * @param:id
     * @return: int
     * @date: 2019/11/7
     */
    @Override
    public int deleteById(Integer id) {


        //在对数据删除前必须先对中间表的数据进行删除
        Integer[] checkItemIds = checkgroupCheckitemMapper.findCheckItemIdsByCheckGroupId(id);
        if (checkItemIds != null && checkItemIds.length > 0) {

            int deleteByCheckGroupId = checkgroupCheckitemMapper.deleteByCheckGroupId(id);
            if (deleteByCheckGroupId == 0) {
                throw new RuntimeException(MessageConstant.EXCEPION);
            }
        }
        List<Integer> setMealIds = setMealCheckGroupMapper.findSetMealIdsByCheckGroupId(id);
        if (setMealIds != null && setMealIds.size() > 0) {
            int deleteBySetMealId = setMealCheckGroupMapper.deleteBySetMealId(id);
            if (deleteBySetMealId == 0) {
                throw new RuntimeException(MessageConstant.EXCEPION);
            }
        }
        int deleteById = checkGroupMapper.deleteById(id);
        if (deleteById == 0) {
            return deleteById;
        }
        //删除数据库的同时对redis中的数据进行删除
        List<CheckGroup> checkGroupList = redisTemplate.boundListOps("checkGroupList").range(0, -1);
        for (CheckGroup Group : checkGroupList) {
            if (Group.getId().equals(id)) {
                redisTemplate.boundListOps("checkItemList").leftPop();
            }
        }
        return deleteById;
    }

    /**
     * 查询所有
     * @return:List<CheckItem>
     * @date: 2019/11/8
     */
    @Override
    public List<CheckGroup> findAll() {
        //从redis中调数据
        List<CheckGroup> checkGroupList = redisTemplate.boundListOps("checkGroupList").range(0, -1);
        return checkGroupList;
    }
}
